/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package oauth2

import (
	"net/http"
	"io/ioutil"
	"encoding/json"
	"gitee.com/tugoer/orivil/wechat"
)

type Response struct {
	User
	wechat.Error
}

type User struct {
	ID         int
	//AppID      string `gorm:"index" json:"appid"`
	Openid     string `gorm:"index" json:"openid"`
	Nickname   string `json:"nickname"`
	Sex        int    `gorm:"index" json:"sex"`
	Province   string `json:"province"`
	City       string `json:"city"`
	Country    string `json:"country"`
	HeadImgUrl string `json:"headimgurl"`
	UnionID    string `gorm:"index" json:"unionid"`
}

// token 必须是在 scope 为 "snsapi_userinfo" 下获得的(即用户点击确认授权后)才有效
func GetUserInfo(token *AuthAccessToken) (user *User, err error) {
	return getUser("https://api.weixin.qq.com/sns/userinfo?lang=zh_CN&access_token=" + token.AccessToken + "&openid=" + token.Openid)
}

func getUser(Url string) (user *User, err error) {
	res, err := http.Get(Url)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	resp := &Response{}
	err = json.Unmarshal(data, resp)
	if err != nil {
		return nil, err
	} else {
		if resp.ErrCode != 0 {
			return nil, resp.Error
		} else {
			return &resp.User, nil
		}
	}
}

// token 为公众号通过 appid 及 app secret 换取而来, 非用户授权获得的 token,
// openid 必须是已关注公众号的用户
func GetSubscribeUserInfo(token, openid string) (user *User, err error) {
	return getUser("https://api.weixin.qq.com/cgi-bin/user/info?lang=zh_CN&access_token="+token+"&openid=" + openid)
}